package cn.pw.test.com.news.fragment;

import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;

import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import java.util.List;

import cn.pw.test.com.news.R;
import cn.pw.test.com.news.adapter.CurrencyNewsletterAdapter;
import cn.pw.test.com.news.adapter.NewsletterAdapter;
import cn.pw.test.com.news.bean.CurrencyNewsletterBean;
import cn.pw.test.com.news.bean.NewsletterBean;
import cn.pw.test.com.news.server.NewsBack;
import cn.pw.test.com.news.server.NewsGlobal;
import tech.com.commoncore.base.BaseFragment;

public class NewsletterFragment extends BaseFragment {

    private SmartRefreshLayout smartRefresh;
    private RecyclerView contentRecycler;

    private NewsletterAdapter newsletterAdapter;

    private List<NewsletterBean> contentList;

    public static NewsletterFragment newInstance() {
        NewsletterFragment fragment = new NewsletterFragment();
        return fragment;
    }

    @Override
    public int getContentLayout() {
        return R.layout.fragment_newsletter;
    }

    @Override
    public void initView(Bundle savedInstanceState) {
        smartRefresh = mContentView.findViewById(R.id.smart_refresh_layout);
        contentRecycler = mContentView.findViewById(R.id.content_recycler_view);

        newsletterAdapter = new NewsletterAdapter(R.layout.news_layout_item_newsletter);
        contentRecycler.setLayoutManager(new LinearLayoutManager(mContext));
        contentRecycler.setAdapter(newsletterAdapter);

        smartRefresh.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshLayout) {
                requestData();
            }
        });

        if (contentList == null || contentList.isEmpty()) {
            smartRefresh.autoRefresh();
        }
    }

    private void requestData() {
        NewsGlobal.getNewsImp().requestNewsletter(4, 20, new NewsBack<List<NewsletterBean>>() {
            @Override
            public void onBack(List<NewsletterBean> beans, String err) {
                smartRefresh.finishRefresh();
                contentList = beans;
                if (beans != null && !beans.isEmpty()) {
                    newsletterAdapter.replaceData(contentList);
                    newsletterAdapter.notifyDataSetChanged();
                }
            }
        });
    }
}
